package com.gujiangbo.dao.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gujiangbo.dao.UserDaoService;
import com.gujiangbo.entity.AcctUsers;
import com.gujiangbo.mapper.UserMapper;
import com.gujiangbo.request.UserInVo;
import com.gujiangbo.cache.CacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@Repository
@Slf4j
public class UserDaoServiceImpl extends ServiceImpl<UserMapper, AcctUsers> implements UserDaoService {

    @Resource
    private CacheService cacheService;

    @Override
    public AcctUsers queryUser(UserInVo userInVo) {
        AcctUsers params = new AcctUsers();
        params.setUAddr(userInVo.getAddress());
        params.setUId(userInVo.getId());
        params.setUName(userInVo.getName());
        String jsonObj = cacheService.get(params.getUId());
        if (StringUtils.isNotBlank(jsonObj)) {
            try {
                return JSONObject.parseObject(jsonObj, AcctUsers.class);
            } catch (Exception e) {
                log.error(e.getMessage());
            } finally {
                cacheService.close();

            }
        }
        return this.getOne(new QueryWrapper<AcctUsers>().setEntity(params));

    }

    @Override
    public void batchUsers(List<AcctUsers> list, int batchSize) {
        list.forEach(items -> cacheService.save(items.getUId(), JSONObject.toJSONString(items)));
        if (cacheService.isOpen()) {
            cacheService.close();
        }
        this.saveBatch(list, batchSize);
    }

    @Override
    public boolean updateByID(AcctUsers users) {
        AcctUsers query = new AcctUsers();
        query.setUId(users.getUId());
        int value = this.baseMapper.update(users, new QueryWrapper<AcctUsers>().setEntity(query));
        boolean flag = cacheService.save(users.getUId(), JSONObject.toJSONString(users));
        return value > 0 && flag;
    }

    @Override
    public AcctUsers queryUsersByMobiles(String requestMap) {
        return this.baseMapper.queryUsersByMobile(requestMap);
    }
}
